<?php
namespace App\Repositories\BLL;
use App\Repositories\BLL\Repository;
use App\Models\Wechat\Wall;
use Illuminate\Support\Facades\DB;

class WallBLL extends Repository
{		
	public function model()
	{
		return Wall::class;
	}
	
	public function ajaxIndex($currentRouteName)
	{
		// datatables请求次数
	    	$draw = request('draw', 1);
	    	// 开始条数
		$start = request('start',config('admin.global.list.start'));
		// 每页显示数目
		$length = request('length',config('admin.global.list.length'));
		// 排序
	    $order['name'] = request('columns.' .request('order.0.column',0) . '.name');
	    $order['dir'] = request('order.0.dir','asc');

	    $search['value'] = request('search.value','');

	    $search['regex'] = request('search.regex',false);

	    $wall = $this->model;

	    // 搜索框中的值
	    if ($search['value']) {
	        if($search['regex'] == 'true'){
	            $wall = $wall->where('name', 'like', "%{$search['value']}%");
	        }else{
	            $wall = $wall->where('name', $search['value']);
	        }
	    }

	    $count = $wall->count();

	    $wall = $wall->orderBy($order['name'], $order['dir']);
    		$walls = $wall->offset($start)->limit($length)->get();
			
		$pointPost = strrpos($currentRouteName,'.');
		$parentUrl = substr($currentRouteName,0,$pointPost);
		if ($walls) {
			foreach ($walls as &$v) {
				$v->actionButton = $v->getListActionButton($currentRouteName);
				if(empty($v['qr_code'])){
					$v->actionButton = $v->actionButton.$this->getQrButton($parentUrl, $v->id);
				}
			}
		}

	    	//datatables固定返回格式
	    	return [
	        'draw' => $draw,
	        'recordsTotal' => $count,
	        'recordsFiltered' => $count,
	        'data' => $walls,
	    ];
	}

	private function getQrButton($parentUrl,$id){
		$thisUrl = $parentUrl.'.createQrCode';
		if(sp_check_auth($thisUrl)){
			return '<a class="btn btn-info btn-xs" href="'.route($thisUrl,['id'=>$id]).'"><i class="fa fa-edit"></i> 二维码</a> ';
		}
		return '';
	}

	public function createEntity($attributes)
	{
		$result = $this->create($attributes);
		if ($result) {
			flash('添加微信墙成功');
		}else{
			flash('添加微信墙失败','error');
		}
		return $result;
	}
	
	public function editView($id)
	{
		$wall = $this->find($id);
		if ($wall) {
			return $wall;
		}
		abort(404);
	}

	public function updateEntity($attributes,$id,$successMsg = "修改成功",$errorMsg = "修改失败")
	{
		$result = $this->update($attributes,$id);
		if ($result) {
			flash($successMsg);
		}else{
			flash($errorMsg,'error');
		}
		return $result;
	}

	public function destroyEntity($id)
	{
		$result = $this->delete($id);
		if ($result) {
			flash('修改成功');
		}else{
			flash('修改失败','error');
		}
		return $result;
	}
	
	/**
	 * 获取所有角色
	 */
	public function getAllEntity()
	{
		$walls = $this->all();
		return $walls;
	}
}